<script setup>
import { useApi } from "../../composables/useApi.js"
import showTost from "@/components/toast/index.js"
import { storeToRefs } from "pinia"
import { useAppStore } from "../../store/app.js"

const appStore = useAppStore()

const { nationArr, sexArr } = storeToRefs(appStore)
import { reactive, ref } from "vue"
import TeatherRightDrawaer from "@/pages/platform/components/teatherRightDrawaer.vue"
import GradeRightDrawear from "@/pages/platform/components/gradeRightDrawear.vue"
import GradeHeader from "@/pages/platform/components/gradeHeader.vue"
import StandarGradeHeader from "@/pages/platform/components/standarGradeHeader.vue"
import StandardGradeDrawear from "@/pages/platform/components/standardGradeDrawear.vue"
import TimesManage from "@/pages/platform/times-manage.vue"
import { router } from "@/plugins/1.router/index.js"
import * as XLSX from "xlsx"
import moment from "moment/moment.js"
import { getStudentList } from "@/api/student.js"
import { standardAddModify, standardDelete } from "@/api/standard.js"
//基本数据list
let list = ref([])
let total = ref(0) //总数
const selected = ref([])
let queryFrom = ref({
  page: 1,
  limit: 20,
  student_id: "",
  student_name: "",
  grade_id: "",
  class_id: "",
  examcourse_id: "",
})

const headers = [
  {
    title: "学生姓名",
    key: "studentRealName",
    width: "240px",
    align: "start",
  },
  {
    title: "学生ID",
    width: "240px",
    align: "start",
    key: "student_id",
  },
  {
    title: "年级",
    width: "240px",
    align: "start",
    key: "gradeTitle",
  },
  {
    title: "班级",
    width: "240px",
    align: "start",
    key: "classTitle",
  },
  {
    title: "考试时间",
    width: "240px",
    align: "start",
    key: "examinationTime",
  },
  {
    title: "语文分数",
    width: "240px",
    align: "start",
    key: "languageScore",
  },
  {
    title: "数学分数",
    width: "240px",
    align: "start",
    key: "mathsScore",
  },
  {
    title: "英语分数",
    width: "240px",
    align: "start",
    key: "englishScore",
  },
  {
    title: "总分",
    width: "240px",
    align: "start",
    key: "totalScore",
  },
  {
    title: "操作",
    align: "end",
    sortable: false,
    key: "options",
  },
]

const examcourse_id = ref(null)
// todo 复制修改列表接口
const getList = async () => {
  const { data } = await useApi("/admin/Api.Standardization/index").post({
    ...queryFrom.value,
    examcourse_id: examcourse_id.value,
  })
  total.value = data.value.data.total
  list.value = data.value.data.data.map((item) => {
    return {
      ...item,
      id: item.standardization_id,
    }
  })
  console.log(list.value)
}

const dialogFlag = ref(false)
// 头部表单回调
const onChange = (val) => {
  let data = JSON.parse(JSON.stringify(val))
  queryFrom.value = { ...queryFrom.value, ...data }
  getList()
}
const isConfirmDialogVisible = ref(false)
// 删除确认弹窗
const onHandleDelete = (val) => {
  console.log(val)
  let ids = val.data.map((item) => item.standardization_id).toString()
  standardDelete({ standardization_id: ids }).then((res) => {
    showTost("删除成功", { duration: 3000, type: "success" })
    queryFrom.value.page = 1
    isConfirmDialogVisible.value = false
    if (val.type == "detail") {
      dialogFlag.value = false
    }
    getList()
  })
}
const selectedItems = ref([])

// 确认弹窗文本
const confirmMsg = ref("")
const currentOptionData = ref({})

// 打开删除弹窗
const onHandleDialog = (type) => {
  if (type == "delete") {
    console.log(selectedItems)
    if (selectedItems.value.length == 0) return
    let data = list.value.filter((item) =>
      selectedItems.value.find((val) => val == item.id),
    )
    console.log(data)
    currentOptionData.value = {
      data: data,
      type: "list",
    }
    confirmMsg.value = `确认删除${data
      .map((item) => item.studentRealName)
      .toString()}的信息吗?`
    isConfirmDialogVisible.value = true
  } else if (type == "openSecondPage") {
    router.push("/platform/times-manage?type=1")
  } else {
    addDialogFlag.value = true
  }
}
// 详情数据
const detailData = ref({})
const viewDetail = async (item) => {
  console.log(item)
  const { data } = await useApi("/admin/Api.Standardization/detail").post({
    standardization_id: item.standardization_id,
  })
  console.log(data)
  detailData.value = data.value.data
  dialogFlag.value = true
}
// 添加教师弹窗falg
const addDialogFlag = ref(false)
const refVForm = ref()

// 下载模板
const downLoadTemplate = async () => {
  const { data } = await useApi("/admin/Base/downFile").post({ type: 5 })
  console.log(data.value)
  if (data.value.status == 200) {
    const link = document.createElement("a")
    link.href = data.value.data.fileUrl
    link.download = data.value.data.fileName
    link.target = "_blank" // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click()
  }
}
// 新增取消回调
const resetForm = () => {
  refVForm.value?.reset()
  addDialogFlag.value = false
}

const valid = ref(false)
const form = reactive({
  student_id: "", //学生ID
  examinationTime: "", //考试时间
  languageScore: "", //语文成绩
  mathsScore: "", //数学升级
  englishScore: "", //英语成绩
  totalScore: "", //总分
  examcourse_id: "", //考试场次ID
  classTitle: "",
  gradeTitle: "",
})
watch(
  () => form.student_id,
  (val) => {
    console.log(val)
    if (val == null) {
      form.classTitle = ""
      form.gradeTitle = ""
      return
    }
    let item = studentList.value.find((item) => item.student_id == val)
    form.classTitle = item.classTitle
    form.gradeTitle = item.gradeTitle
  },
)
let totalScore = computed(() => {
  return (
    Number(form.languageScore) +
    Number(form.mathsScore) +
    Number(form.englishScore)
  )
})

const confirmAdd = async (args) => {
  console.log(totalScore.value)
  if (!valid.value) return
  standardAddModify({
    ...form,
    examcourse_id: examcourse_id.value,
    totalScore: totalScore.value,
  }).then((res) => {
    refVForm.value?.reset()
    addDialogFlag.value = false
    showTost("新增成功", { duration: 3000, type: "success" })
    queryFrom.value.page = 1
    getList()
  })
}
let sexList = ref(["男", "女"])
const onHandleEdit = () => {
  queryFrom.value.page = 1
  getList()
}
// getList()
const required = (value, name) => !!value || `${name}为必填字段`

const import_page = ref(1)
const import_limit = ref(10)
const import_percent = ref(0)
const loading = ref(false)
function formatDate(str) {
  const monthMap = {
    Jan: '01', Feb: '02', Mar: '03', Apr: '04', May: '05', Jun: '06',
    Jul: '07', Aug: '08', Sep: '09', Oct: '10', Nov: '11', Dec: '12'
  };
  console.log(str)
  const parts = str.toString().split(' ');
  const year = parts[3];
  const month = monthMap[parts[1]];
  const day = parts[2];
  return `${year}-${month}-${day}`;
}

const partPost = async (tableData) => {
  for(let item of tableData){
    const input =item['考试时间'];
    item['考试时间'] = formatDate(input)
    item.classTitle = item['班级']
    item.gradeTitle = item['年级']
    item.student_id = item['学生ID']
  }
  let perdata = []
  for (
    let i = (import_page.value - 1) * import_limit.value;
    i < import_page.value * import_limit.value;
    i++
  ) {
    if (tableData[i]) {
      perdata.push(tableData[i])
    }
  }
  console.log(JSON.stringify({ examcourse_id:examcourse_id.value,list:[...perdata] }))
  perdata.examcourse_id = examcourse_id.value
  let total_page = Math.ceil(tableData.length / import_limit.value)
  import_percent.value = Math.ceil((import_page.value * 100) / total_page)
  loading.value = true
  const { data } = await useApi("/admin/Api.Standardization/upload").post(
    JSON.stringify({ examcourse_id:examcourse_id.value,list:[...perdata] })
  )
  if (data.value.status == 200) {
    if (import_page.value <= total_page - 1) {
      import_page.value = import_page.value + 1
      partPost(data)
    } else {
      // this.dialog.importDialogstatus = false;
      showTost("导入完成", { duration: 3000, type: "success" })
      addDialogFlag.value = false
      loading.value = false
      getList()
    }
  }
}

const onChangePage = (val) => {
  queryFrom.value.page = val.page
  queryFrom.value.limit = val.limit
  getList()
}
const drawaerDelete = async (val) => {
  console.log(val)
  currentOptionData.value = {
    data: [val],
    type: "detail",
  }
  confirmMsg.value = `确认删除${val.studentRealName}的信息吗`
  isConfirmDialogVisible.value = true
}
const viewDetailClassStudent = (type, item) => {
  showTost("暂未开放")
  if (type == "class") {
  }
}
// 二级页面显示开关
const secondPageShowFlag = ref(false)
const onHandleSecondPage = () => {
  secondPageShowFlag.value = true
}
const changeId = (val) => {
  examcourse_id.value = val
  getList()
}
const httpRequest = (e) => {
  let file = e.file // 文件信息
  if (!file) {
    return false
  } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    // 格式根据自己需求定义
    this.$message.error("上传格式不正确，请上传xls或者xlsx格式")
    return false
  }
  const fileReader = new FileReader()
  fileReader.onload = (ev) => {
    try {
      const data = ev.target.result
      const workbook = XLSX.read(data, {
        // 以字符编码的方式解析
        type: "binary",
        cellDates: true,
      })
      // 取第一张表
      console.log(workbook)
      const exlname = workbook.SheetNames[0]
      const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]) // 生成json表格内容
      console.log(exl)
      partPost(exl)
      // 将 JSON 数据挂到 data 里
      let arr = []
      exl.forEach(item => {
        arr.push(item.name)
      })
      console.log(arr)
    } catch (e) {
      console.log("error")
      return false
    }
  }
  fileReader.readAsBinaryString(file)
}

const onlyAllowNumbers = (event) => {
  const key = event.key
  // 检查按键是否为数字或控制键（如 backspace）
  if (!/^\d$/.test(key) && event.key !== "Backspace" && event.key !== "Tab") {
    event.preventDefault()
  }
}
const filterInput = (key) => {
  // 仅保留数字
  form[key] = form[key].replace(/\D/g, "")
}

/**  获取学生列表*/
const studentList = ref([])
const getStudentListProp = async () => {
  getStudentList({ page: 1, limit: 999 }).then((res) => {
    studentList.value = res.data.value.data
    console.log(studentList.value)
  })
}
getStudentListProp()
</script>

<template>
  <div class="content">
    <!--    考试场次管理-->
    <times-manage v-if="secondPageShowFlag"></times-manage>
    <!--   Ought to 修改右侧抽屉-->
    <standard-grade-drawear
      @onHandleDelete="drawaerDelete"
      @onHandleEdit="onHandleEdit"
      :detailData="detailData"
      @update:isDrawerOpen="dialogFlag = $event"
      :is-drawer-open="dialogFlag"
      :student-list="studentList"
    ></standard-grade-drawear>

    <ConfirmDialog
      :handleData="currentOptionData"
      v-model:isDialogVisible="isConfirmDialogVisible"
      @confirm="onHandleDelete"
      :confirm-msg="confirmMsg"
      :confirmation-question="confirmMsg"
      cancel-msg="Unsubscription Cancelled!!"
    />
    <!--    Ought to 修改顶部检索栏部分-->
    <!-- 头部 -->
    <standar-grade-header
      title="标化成绩"
      button-text="添加信息"
      @onChange="onChange"
      @changeId="changeId"
      @onHandle="onHandleDialog"
    />
    <VDataTable
      v-model="selectedItems"
      :headers="headers"
      :items="list"
      :items-per-page="100"
      item-key="id"
      show-select
      class="text-no-wrap"
    >
      <template #item.options="{ item }">
        <div class="d-flex align-center options-right-display">
          <div class="d-flex flex-column ms-3 cursor-pointer">
            <i @click="viewDetail(item)" class="ri-menu-line"></i>
          </div>
        </div>
      </template>
    </VDataTable>
    <PaginationVue
      @onChange="onChangePage"
      :current-page="queryFrom.page"
      :page-size="queryFrom.limit"
      :total="total"
    />
    <!--    添加对话框-->
    <VDialog :persistent="true" max-width="600" :model-value="addDialogFlag">
      <VDivider/>
      <VCard>
        <PerfectScrollbar :options="{ wheelPropagation: false }" class="h-60">
          <VCardText>
            <elUpload
              ref="importExcelRef"
              :limit="1"
              :show-file-list="false"
              class="uploadExcelContent"
              :http-request="httpRequest"
            >
              <VBtn type="submit" color="primary" class="me-4 mb-5">
                <i
                  style="font-size: 24px; margin-right: 6px"
                  class="ri-upload-cloud-fill"
                ></i>
                上传Excel文件
              </VBtn>
            </elUpload>

            <VForm v-model="valid" ref="refVForm" @submit.prevent="confirmAdd">
              <VRow>
                <VCol cols="6">
                  <VTextField
                    v-model="form.student_id"
                    disabled
                    label="学生ID"
                    :rules="[(val) => required(val, '学生ID')]"
                  >
                  </VTextField>
                </VCol>
                <VCol cols="6">
                  <v-autocomplete
                    v-model="form.student_id"
                    :items="studentList"
                    item-title="real_name"
                    item-value="student_id"
                    :rules="[(val) => required(val, '学生姓名')]"
                    class="input-width-height"
                  >
                    <template v-slot:label>
                      <span>学生姓名</span>
                      <span style="color: red; margin-left: 4px">*</span>
                    </template>
                  </v-autocomplete>
                </VCol>
                <VCol cols="6">
                  <VTextField
                    v-model="form.gradeTitle"
                    disabled
                    label="所属年级"
                  >
                  </VTextField>
                </VCol>
                <VCol cols="6">
                  <VTextField
                    v-model="form.classTitle"
                    disabled
                    label="所属班级"
                  >
                  </VTextField>
                </VCol>
                <VCol cols="6">
                  <AppDateTimePicker
                    class="input-width-height"
                    v-model="form.examinationTime"
                    label="考试时间"
                    placeholder="请选择考试时间"
                    :rules="[(val) => required(val, '考试时间')]"
                  >
                    <template v-slot:label>
                      <span>考试时间</span>
                      <span style="color: red; margin-left: 4px">*</span>
                    </template>
                  </AppDateTimePicker>
                </VCol>
                <VCol cols="6">
                  <VTextField
                    v-model="form.languageScore"
                    @keypress="onlyAllowNumbers"
                    @input="() => filterInput('languageScore')"
                    label="语文分数"
                    :rules="[(val) => required(val, '语文分数')]"
                    placeholder="请输入语文分数"
                  >
                    <template v-slot:label>
                      <span>语文分数</span>
                      <span style="color: red; margin-left: 4px">*</span>
                    </template>
                  </VTextField>
                </VCol>

                <VCol cols="6">
                  <VTextField
                    v-model="form.mathsScore"
                    @keypress="onlyAllowNumbers"
                    @input="() => filterInput('mathsScore')"
                    label="数学分数"
                    :rules="[(val) => required(val, '数学分数')]"
                    placeholder="请输入数学分数"
                  >
                    <template v-slot:label>
                      <span>数学分数</span>
                      <span style="color: red; margin-left: 4px">*</span>
                    </template>
                  </VTextField>
                </VCol>

                <VCol cols="6">
                  <VTextField
                    v-model="form.englishScore"
                    label="英语分数"
                    @keypress="onlyAllowNumbers"
                    @input="() => filterInput('englishScore')"
                    :rules="[(val) => required(val, '英语分数')]"
                    placeholder="请输入英语分数"
                  >
                    <template v-slot:label>
                      <span>英语分数</span>
                      <span style="color: red; margin-left: 4px">*</span>
                    </template>
                  </VTextField>
                </VCol>
                <VCol cols="6">
                  <VTextField
                    disabled
                    v-model="totalScore"
                    label="总分"
                    :rules="[(val) => required(val, '总分')]"
                    placeholder="请输入总分"
                  />
                </VCol>
                <VDivider/>
                <VCol cols="12">
                  <div class="d-flex justify-end">
                    <VBtn color="secondary"
                          type="reset"
                          variant="tonal" class="me-4" @click="downLoadTemplate"
                    >
                      下载上传模板
                    </VBtn>
                    <VBtn color="secondary"
                          type="reset"
                          variant="tonal" class="me-4" @click="resetForm"
                    >
                      取消
                    </VBtn>
                    <VBtn type="submit" color="primary" class="me-4">
                      添加
                    </VBtn>
                  </div>
                </VCol>
              </VRow>
            </VForm>
          </VCardText>
        </PerfectScrollbar>
      </VCard>
    </VDialog>
  </div>
</template>

<style lang="scss" scoped></style>
